package com.group7.mall.handler;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

    // 在controller中new一个？
    private final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 假设客户端在连接时发送了userId作为查询参数或消息体的一部分
        String userId = getUserIdFromSession(session); // 实现此方法以从session中提取userId
        sessions.put(userId, session);
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理客户端发送的消息...
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        String userId = String.valueOf(sessions.get(session)); // 获取与session关联的userId
        if (userId != null) {
            sessions.remove(userId);
        }
    }

    // 根据userId发送消息的方法
    public void sendMessageToUser(String userId, String message) throws IOException {
        WebSocketSession session = sessions.get(userId);
        if (session != null && session.isOpen()) {
            session.sendMessage(new TextMessage(message));
        } else {
            System.out.println("找不到用户WebSocketSession或已关闭：" + userId);
        }
    }

    // 辅助方法，用于从WebSocketSession中提取userId，具体实现取决于你的协议设计
    private String getUserIdFromSession(WebSocketSession session) {
        // 这里是示例代码，你需要根据你的实际情况来实现这个方法
        // 例如，你可以从session的属性、查询参数或消息体中获取userId
        return "someUserId"; // 返回从session中提取的userId
    }
}